<template>

    <loginView v-if="isGoLogin" @signin="doSignIn"></loginView>
    <userInfoView v-else @singout="doSignOut" :userInfo="userInfo"></userInfoView>
</template>

<script>
    import loginView from '../user/login.vue';
    import userInfoView from '../user/userInfo.vue';
    import { Toast } from 'mint-ui';
    import cookie from '../../util/cookie.js';
    export default {
        data() {
            return {
                isGoLogin: false,
                userInfo: {}
            }
        },
        created() {
            var userToken = cookie.getCookie('token');

            if (userToken != '' && userToken != null) {
                this.getUserInfoByToken();
            } else {
                this.isGoLogin = true;
            }
        },
        methods: {
            async getUserInfoByToken() {
                await this.$http.post('/getUserInfoByToken', cookie.getCookie('token')).then(data => {
                    if (data.body.status === 0) {
                        this.userInfo = data.body.data;
                        this.isGoLogin = false;
                    } else {
                        this.isGoLogin = true;
                    }
                    localStorage.setItem('user_info', JSON.stringify(this.userInfo));
                }).catch(data => {
                    Toast('请求超时，请检查您的网络');
                    this.isGoLogin = true;
                });
            },
            doSignOut() {
                this.isGoLogin = true;
            },
            // 使用localStorage,避免每次都发出请求
            doSignIn() {
                var userInfo = localStorage.getItem('user_info');
                if (userInfo != '' && userInfo != null && userInfo != 'undefined') {
                    this.userInfo = userInfo;
                }else {     
                    console.log('http请求获取用户信息');
                    this.getUserInfoByToken();
                }


                var carInfo = localStorage.getItem('car');
                if(carInfo == '' || carInfo == null || carInfo == 'undefined'){
                    console.log('http请求获取用户购物车信息');
                    this.$http.get('/getcarinfo/1111').then(data => {
                        if (data.body.status === 0) {
                            this.$store.commit('initCarInfo', data.body.data);
                        }
                    }).catch({
                    });
                }

                this.isGoLogin = false;
            }

        },
        components: {
            loginView,
            userInfoView
        }
    }
</script>


<style lang="scss" scoped>

</style>